﻿using System;
using UnityEngine;

namespace SG
{
    public class AudioSourceFade : MonoBehaviour
    {
        private AudioSource Music;
        private float volumeDelta;
        private float targetvolume;
        private bool isfading;

        void Start()
        {
            Music = GetComponent<AudioSource>();
            SetVolume();
            if (Music == null)
            {
                Debug.LogError("Music AudioSource is Null");
            }
            volumeDelta = 0;
            isfading = false;
        }

        // Update is called once per frame
        void Update()
        {
            if (!isfading) return;
            if (Math.Abs(Music.volume - targetvolume) >= Math.Abs(volumeDelta))
            {
                Music.volume += (float)volumeDelta;
            }
            else
            {
                Music.volume = targetvolume;
                isfading = false;
            }
        }

        public AudioSource GetAudioSource()
        {
            return Music;
        }

        public void SetVolume(float volume = -1)
        {
            if (volume == -1)
                volume = AudioManager.Instance().GetBGMVolume();
            Music.volume = volume;
        }

        public float GetAudioSourceVolume()
        {
            return Music.volume;
        }

        public void FadeMusic(float targetVolume/*0-1*/, float durtime/*seconds*/)
        {
            Debug.Log("Music fade set target = " + targetVolume);
            targetvolume = targetVolume;
            if (Music == null) return;
            float timedelta = durtime / Time.deltaTime;
            if (timedelta > 0)
                volumeDelta = (targetVolume - Music.volume) / timedelta;
            else
            {
                volumeDelta = (targetVolume - Music.volume);
            }

            isfading = true;
        }

        public void FadeIn(float time)
        {
            FadeMusic(1, time);
        }

        public void FadeOut(float time)
        {
            FadeMusic(0, time);
        }


    }
}
